<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/10/19
 * Time: 14:21
 */

namespace common\business;

use common\consts\CommonResources;
use common\consts\Consts;
use common\models\Log;
use common\models\User;
use Yii;
use common\models\qywx\QywxUser;
use common\result\ActionResult;
use yii\helpers\Json;

class QywxUserService
{
    /**
     * @var QywxApiService
     */
    protected $_apiService;

    /**
     * QywxUserService constructor.
     * @param QywxApiService $apiService
     */
    public function __construct(QywxApiService $apiService = null)
    {
        $this->_apiService = $apiService;
        if (!isset($this->$apiService) || $this->_apiService == null){
            $this->_apiService = new QywxApiService();
        }
    }

    /**
     * @param $userInDb QywxUser
     * @return ActionResult
     */
    public function update(QywxUser $userInDb){
        $action = Yii::t('app' , 'Update');
        $modelClass = Yii::t('app' , 'User');

        $oldObj = QywxUser::findOne([
            'qywx_user_id' => $userInDb->qywx_user_id,
        ]);
        $compareResult = CommonHelper::compareObjectAttributes($oldObj, $userInDb, [
            'qywx_user_name',
            'qywx_user_position',
            'qywx_user_mobile',
            'qywx_user_gender',
            'qywx_user_email',
            'qywx_user_isleader',
            'qywx_user_telephone',
            'qywx_user_english_name',
            'qywx_user_extattr',
        ]);
        if (!$compareResult->isChanged){
            return new ActionResult(true, Yii::t('app', CommonResources::$OBJECT_NOT_CHANGED), true);
        }

        try {
            $updateArr = [
                'userid' => $userInDb->qywx_user_userid,
                'name' => $userInDb->qywx_user_name,
                'position' => $userInDb->qywx_user_position,
                'mobile' => $userInDb->qywx_user_mobile,
                'gender' => $userInDb->qywx_user_gender,
                'email' => $userInDb->qywx_user_email,
                'isleader' => $userInDb->qywx_user_isleader,
                'telephone' => $userInDb->qywx_user_telephone,
                'english_name' => $userInDb->qywx_user_english_name,
                'extattr' => $userInDb->qywx_user_extattr,
            ];
            $infoJson = Json::encode($updateArr);
            $apiResult = $this->_apiService->updateUser($infoJson);

            if(!$apiResult->isSuccess){
                return $apiResult;
            }

            $newLog = new Log([
                'action' => CommonResources::ACTION_MSG($action, $modelClass),
                'memo' => $compareResult->message,
            ]);
            CommonHelper::persistRecordWithLog($userInDb, $newLog);

            return new ActionResult(true, CommonResources::ACTION_SUCCESS_MSG($action, $modelClass));
        } catch (\Exception $e) {
            return new ActionResult(false, $e->getMessage(), false, $e);
        }
    }

    /**
     * @param QywxUser $user
     * @return ActionResult
     */
    public function create(QywxUser $user){
        $action = Yii::t('app' , 'Create');
        $modelClass = Yii::t('app' , 'User');

        try {
            $objArr = [
                'userid' => $user->qywx_user_userid,
                'name' => $user->qywx_user_name,
                'position' => $user->qywx_user_position,
                'mobile' => $user->qywx_user_mobile,
                'department' => $user->qywx_user_department,
                'order' => $user->qywx_user_order,
                'gender' => $user->qywx_user_gender,
                'email' => $user->qywx_user_email,
                'isleader' => $user->qywx_user_isleader,
                'telephone' => $user->qywx_user_telephone,
                'english_name' => $user->qywx_user_english_name,
                'extattr' => $user->qywx_user_extattr,
                'enable' => $user->qywx_user_status,
            ];
            $infoJson = Json::encode($objArr);

            $apiResult = $this->_apiService->createUser($infoJson);

            if(!$apiResult->isSuccess){
                return $apiResult;
            }

            $newLog = new Log([
                'action' => CommonResources::ACTION_MSG($action, $modelClass),
                'memo' => $infoJson,
            ]);
            CommonHelper::persistRecordWithLog($user, $newLog);

            return new ActionResult(true, CommonResources::ACTION_SUCCESS_MSG($action, $modelClass));
        } catch (\Exception $e) {
            return new ActionResult(false, $e->getMessage(), false, $e);
        }
    }


    /**
     * @param $user QywxUser
     * @return ActionResult
     */
    public function delete(QywxUser $user){
        $action = Yii::t('app' , 'Update');
        $modelClass = Yii::t('app' , 'User');

        try {
            $apiResult = $this->_apiService->deleteUser($user->qywx_user_userid);

            if(!$apiResult->isSuccess){
                return $apiResult;
            }

            $objArr = [
                'userid' => $user->qywx_user_userid,
                'name' => $user->qywx_user_name,
                'position' => $user->qywx_user_position,
                'mobile' => $user->qywx_user_mobile,
                'department' => $user->qywx_user_department,
                'order' => $user->qywx_user_order,
                'gender' => $user->qywx_user_gender,
                'email' => $user->qywx_user_email,
                'isleader' => $user->qywx_user_isleader,
                'telephone' => $user->qywx_user_telephone,
                'english_name' => $user->qywx_user_english_name,
                'extattr' => $user->qywx_user_extattr,
                'enable' => $user->qywx_user_status,
            ];
            $infoJson = Json::encode($objArr);
            $newLog = new Log([
                'action' => CommonResources::ACTION_MSG($action, $modelClass),
                'memo' => $infoJson,
            ]);
            CommonHelper::deleteRecordWithLog($user, $newLog);

            return new ActionResult(true, CommonResources::ACTION_SUCCESS_MSG($action, $modelClass));
        } catch (\Exception $e) {
            return new ActionResult(false, $e->getMessage(), false, $e);
        }
    }

    /**
     * @param $userIdArr array
     * @return ActionResult
     */
    public function batchDelete($userIdArr){
        $action = Yii::t('app' , 'Batch Delete');
        $modelClass = Yii::t('app' , 'User');

        try {
            $objArr = [
                'useridlist' => $userIdArr,
            ];
            $infoJson = Json::encode($objArr);

            $apiResult = $this->_apiService->batchDeleteUser($infoJson);

            if(!$apiResult->isSuccess){
                return $apiResult;
            }

            foreach ($userIdArr as $userId){
                $user = QywxUser::findOne([
                   'qywx_user_userid' => $userId
                ]);
                $newLog = new Log([
                    'action' => CommonResources::ACTION_MSG($action, $modelClass),
                    'memo' => $infoJson,
                ]);
                CommonHelper::deleteRecordWithLog($user, $newLog);
            }

            return new ActionResult(true, CommonResources::ACTION_SUCCESS_MSG($action, $modelClass));
        } catch (\Exception $e) {
            return new ActionResult(false, $e->getMessage(), false, $e);
        }
    }


    public function getByDepartmentId($departmentId){
        $action = Yii::t('app' , 'Find');
        $modelClass = Yii::t('app' , 'User');

        try {
//            此处处理回调，更新数据库id到对象中
            $totalResult = new ActionResult();
            $successCallback = function($errcode, $errmsg, $usersArr) use ($totalResult) {
                if(sizeof($usersArr) == 0) {
                    return new ActionResult(true, CommonResources::NO_JSON_CONTENT_FOUND());
                }
                foreach ($usersArr as $user_item){
                    $userInDb = QywxUser:: findOne([
                        'qywx_user_userid' => $user_item['userid'],
                    ]);
                    if ($userInDb != null){
                        $syncResult = QywxHelper::syncSingleQywxUserByArr($userInDb, $user_item);
                        $totalResult->addSubResult($syncResult);
                        continue;
                    }

                    $newResult = QywxHelper::newQywxUserByArr($user_item);
                    $totalResult->addSubResult($newResult);
                }
                return $totalResult;
            };

            $apiResult = $this->_apiService->getUsersByDepartmentId($departmentId, $successCallback);
            if(!$apiResult->isSuccess){
                return $apiResult;
            }

            return $totalResult;
        } catch (\Exception $e) {
            return new ActionResult(false, $e->getMessage(), false, $e);
        }
    }
}